package com.Demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-12-04
 * Time: 14:57
 */

//阻塞队列 基于循环队列实现的
class MyBlockQueue {
    int[] arr = new int[1000];
    //首指针
    int head = 0;
    //尾
    int tail = 0;
    //有效数据个数
    int size = 0;

    //wait和notify实现阻塞 前提是配合synchronized使用
    Object locker = new Object();

    //入队
    public void push(int val) throws InterruptedException {
        //判断是否未满
        if (size == arr.length){
            synchronized (locker){
                locker.wait();
            }
        }
        arr[tail] = val;
        tail++;
        //当tail走到了最后一个位置的时候 重新设为零
        if (tail >= arr.length){
            tail = 0;
        }
        size++;
        synchronized (locker){
            locker.notify();
        }
    }

    //出队
    public Integer pull() throws InterruptedException {
        //判断是否为空
        if (size == 0){
           synchronized (locker){
               locker.wait();
           }
        }
        int ret = arr[head];
        head++;
        if (head>=arr.length){
            head = 0;
        }
        size--;
        synchronized (locker){
            locker.notify();
        }
        return ret;
    }
}


//阻塞队列
public class TestDemo1 {

    private static MyBlockQueue queue = new MyBlockQueue();

    //实现一个生产者 消费之模型
    public static void main(String[] args) {
        Thread producer = new Thread(()->{
            int num = 0;
            while (true){
                System.out.println("生成了: " + num);
                try {
                    queue.push(num);
                    num++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();

        Thread customer = new Thread(()->{
            while (true){
                try {
                    int num = queue.pull();
                    System.out.println("消费了：" + num);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }


    //测试循环队列
    public static void main1(String[] args) throws InterruptedException {
        MyBlockQueue queue = new MyBlockQueue();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        queue.push(4);
        queue.push(5);
        System.out.println(queue.pull());

    }
}
